package utils

import (
	"fmt"
	"github.com/shopspring/decimal"
	"math"
	"regexp"
	"strconv"
	"strings"
	"unicode/utf16"
	"unsafe"
)

//string 转int32
func StrToInt(str string) int32 {

	value_int64, _ := strconv.ParseInt(str, 10, 64)
	value_int := *(*int32)(unsafe.Pointer(&value_int64))
	return value_int
}

//string 转int64
func StrToInt64(str string) int64 {

	value_int64, _ := strconv.ParseInt(str, 10, 64)
	return value_int64
}

//string 转float32
func StrToFloat32(str string) float32 {

	value_float64, _ := strconv.ParseFloat(str, 64)
	return float32(value_float64)
}

//string 转float64
func StrToFloat64(str string) float64 {

	value_float64, _ := strconv.ParseFloat(str, 64)
	return value_float64
}

//float64 保留两位小数
func Decimal(num float64) float64 {
	var num2 float64
	decimalValue := decimal.NewFromFloat(0)
	if num < 0 {
		decimalValue = decimal.NewFromFloat(num - 0.005)

	} else {
		decimalValue = decimal.NewFromFloat(num + 0.005)
	}
	//乘100
	decimalValue = decimalValue.Mul(decimal.NewFromInt(100))
	res, _ := decimalValue.Float64()
	num3 := math.Trunc(res)
	decimalValue2 := decimal.NewFromFloat(num3)
	//除100
	decimalValue2 = decimalValue2.Div(decimal.NewFromInt(100))
	num2, _ = decimalValue2.Float64()
	return num2
}

//float32 转string
func FloatToStr(val float32) string {
	s1 := strconv.FormatFloat(float64(val), 'E', -1, 32)
	return s1
}

//float64 转string
func FloatToStr64(val float64) string {
	s1 := strconv.FormatFloat(val, 'f', -1, 64)
	return s1
}

//字符串替换 +替换-  /替换成 _
func Stringtihuan(val string) string {
	val = strings.Replace(val, "+", "-", -1)
	val = strings.Replace(val, "/", "_", -1)
	TrimRightStr := strings.TrimRight(val, "=")
	return TrimRightStr
}

//int64 转string
func Int64string(val int64) string {
	return strconv.FormatInt(val, 10)
}

//int64 转string
func IntToString64(val int64) string {
	s := strconv.FormatInt(val, 10)
	return s
}

// EmojiDecode Emoji字符转表情
func EmojiDecode(s string) string {
	re := regexp.MustCompile("\\\\u[ed][0-9a-f]{3}\\\\u[ed][0-9a-f]{3}")
	result := re.FindAllString(s, -1)
	if len(result) > 0 {
		for k := range result {
			tmp := result[k]
			result[k] = strings.Replace(result[k], "\\u", "0x", -1)
			cov1, _ := strconv.ParseUint(result[k][:6], 0, 32)
			cov2, _ := strconv.ParseUint(result[k][6:], 0, 32)
			covResult := fmt.Sprintf("%c", utf16.DecodeRune(rune(cov1), rune(cov2)))
			s = strings.Replace(s, tmp, covResult, -1)
		}
	}
	return s
}

// EmojiEncode Emoji表情转字符
func EmojiEncode(s string) string {
	ret := ""
	rs := []rune(s)
	for i := 0; i < len(rs); i++ {
		if len(string(rs[i])) == 4 {
			r1, r2 := utf16.EncodeRune(rs[i])
			t1 := "\\u" + fmt.Sprintf("%x", r1)
			t2 := "\\u" + fmt.Sprintf("%x", r2)
			ret += t1 + t2
		} else {
			ret += string(rs[i])
		}
	}
	return ret
}
